package com.example.componets;

import com.alibaba.fastjson.JSON;
import com.example.bean.LogBean;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class LogService {
    @Resource
    private HttpServletRequest request;
    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 切点方法
     */
    @Pointcut("execution(* com.example.controller.TestController.*(..))")
    public void logPointcut() {

    }

    /**
     * 环绕通知
     *
     * @param joinPoint
     */
    @Around("logPointcut()")
    public void around(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        String typeName = signature.getDeclaringTypeName();
        LogBean logBean = new LogBean();

        Method method = signature.getMethod();
        //获取方法注解
        Annotation[] annotations = method.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof ApiOperation) {
                ApiOperation apiOperation = (ApiOperation) annotation;
                log.info("apiOperationValue:{}", apiOperation.value());
                logBean.setMethodName(apiOperation.value());
            }
        }

        //获取请求参数

        logInsert(logBean);
    }

    /**
     * 存储日志
     *
     * @param logBean
     */
    public void logInsert(LogBean logBean) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String params = JSON.toJSONString(request.getParameterMap());
        log.info("params:{}", params);
        logBean.setMethodArgs(params);
        //参数
        mongoTemplate.insert(logBean);
    }
}
